package com.zhang.service.impl;

import com.zhang.dao.UserMapper;
import com.zhang.entity.Address;
import com.zhang.entity.User;
import com.zhang.service.UserService;
import com.zhang.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserServiceImpl implements UserService {
    @Override
    public User selectByEmailAndPwd(String email, String password) {
        SqlSession sqlSession = null;
        User user = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            UserMapper dao = sqlSession.getMapper(UserMapper.class);
            user = dao.selectByEmailAndPwd(email, password);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
        return user;
    }

    @Override
    public boolean regist(User u) {
        SqlSession sqlSession = null;
        boolean result = false;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            UserMapper dao = sqlSession.getMapper(UserMapper.class);
            User user = dao.selectByEmail(u.getEmail());
            if(user == null){
                result = true;
            }
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
        return result;
    }

    @Override
    public void insert(User u) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            UserMapper dao = sqlSession.getMapper(UserMapper.class);
            dao.insert(u);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
    }

    @Override
    public User selectByEmail(String email) {
        SqlSession sqlSession = null;
        User user = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            UserMapper dao = sqlSession.getMapper(UserMapper.class);
            user = dao.selectByEmail(email);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
        return user;
    }
}
